﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace NetServer
{
    public class MyDes
    {
        /// <summary>
        /// 对称加密
        /// </summary>
        /// <param name="str"></param>
        /// <param name="pwd_hex"></param>
        /// <returns></returns>
        public static byte[] doDesByte(String str, String pwd_hex)
        {
            byte[] bb = System.Text.Encoding.Default.GetBytes(str);
            int len = bb.Length;
            if (len % 8 > 0)
            {
                len += 8 - (len % 8);
            }
            byte[] txt = new byte[len];
            for (int i = 0; i < bb.Length; ++i)
                txt[i] = bb[i];
            try
            {
               return ToEncrypt(str, pwd_hex);
            }
            catch (Exception e)
            {
                ErrorRecordFile.WriteError(e);
                return null;
            }
        }
        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="str"></param>
        /// <param name="myKey"></param>
        /// <returns></returns>
        private static byte[] ToEncrypt(string str, string myKey)
        {
            string encryptKeyall = Convert.ToString(myKey);    //定义密钥  
            if (encryptKeyall.Length < 9)
            {
                for (; ; )
                {
                    if (encryptKeyall.Length < 9)
                        encryptKeyall += encryptKeyall;
                    else
                        break;
                }
            }
            string encryptKey = encryptKeyall.Substring(0, 8);
            DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();   //实例化加/解密类对象   
            descsp.Mode = CipherMode.CBC;
            descsp.Padding = PaddingMode.PKCS7;
            byte[] key = Encoding.UTF8.GetBytes(encryptKey); //定义字节数组，用来存储密钥    
            byte[] data = Encoding.UTF8.GetBytes(str);//定义字节数组，用来存储要加密的字符串  
            MemoryStream MStream = new MemoryStream(); //实例化内存流对象      
            //使用内存流实例化加密流对象   
            CryptoStream CStream = new CryptoStream(MStream, descsp.CreateEncryptor(key, key), CryptoStreamMode.Write);
            CStream.Write(data, 0, data.Length);  //向加密流中写入数据      
            CStream.FlushFinalBlock();              //释放加密流      
            return MStream.ToArray();//返回加密后的字符串  
        }
    }
}
